<template>
  <div>
    <base-modal :width="modAlProps.width" :isVisible="props.isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="handleCancle" class="site_modal">
      <template v-slot:body>
        <div class="title-box">
          <div class="tips left">请选择需要合并进来的栏目：</div>
          <div class="tips right">合并后的栏目结构：</div>
        </div>
        <div class="trasfer-fl">
          <div class="trasfer-center trasfer-l">
            <base-tree :treeData="treeData" :fieldNames="fieldNames" :checkedKeys="checkedKeys" :checkStrictly="true"
              :selectable="false" @checked_Keys="checked_Keys"></base-tree>
          </div>
          <div class="trasfer-center trasfer-r">
            <base-tree :selectable="false" :treeData="deletetreeData" :fieldNames="fieldNames" :checkable="false"
              :checkStrictly="true"></base-tree>
          </div>
        </div>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted, watch } from "vue";
import baseModal from "@/components/modal/baseModal.vue";
import baseTree from "@/components/tree/baseTree.vue";
import { dataSourceType, detailDataItemType } from "@/type";
import request from "@/api/index";
import { Modal, message } from "ant-design-vue";
import getOptions_parent from "@/utils/getRelationOptions";
import { useRoute, useRouter } from "vue-router";
//interface
interface Options {
  [propName: string | number]: any,
}
const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
  modelId: {
    type: String,
    default: "",
  },
  channelName: {
    type: String,
    default: "",
  },
});
// route
const route = useRoute();
//data
//模态框数据
const modAlProps = reactive<Options>({
  width: "L",
  title: "合并栏目到：" + props.channelName,
});
//树结构数据
const fieldNames = reactive<dataSourceType>({
  title: "channelName",
  key: "id",
  children: 'children'
});

//模态框button按钮个数和文案修改
const isVisible = ref<Boolean>(false); // 模态框是否可见
let buttons = ref<Options[]>([
  {
    text: "确认合并",
    "html-type": "submit",
  },
]);
let isCancleBtn = ref<Boolean>(false);
const checkedKeys = ref<(string | number | any)[]>([]);
// const upOrgOptions = ref([]);
const upOrgOptions = ref<dataSourceType[]>([]);
const treeData = ref<Options[]>([]);
const deletetreeData = ref<Options[]>([]);

//watch
watch(() => props.channelName, (newVal, oldVal) => {
  modAlProps.title = '合并栏目到：' + newVal + '(目标栏目)';
}, { deep: true })

//获取新增层级树列表
const fetchChannelChannelTree = async () => {
  treeData.value = await request.fetchChannelChannelTree();
  deletetreeData.value = JSON.parse(JSON.stringify(treeData.value));
  disabledParent(treeData.value);

};

const checked_Keys = (obj: dataSourceType) => {
  let checkedNode = obj.e.node;
  let datas = JSON.parse(JSON.stringify(treeData.value));
  loops(datas, obj.checkedKeys.checked);
  deletetreeData.value = JSON.parse(JSON.stringify(datas));
  checkedKeys.value = obj.checkedKeys.checked;
  if (checkedNode && checkedNode.children) {
    checkedKeys.value = loopChildren([checkedNode] || [], obj.e.checked);
  } else {
    checkedKeys.value = obj.checkedKeys.checked;
  }
};
// 递归处理数据
const loops = (datalist: dataSourceType[] = [], ids: dataSourceType[] = []): any => {
  const loop1 = function (data: dataSourceType[]) {
    if (data instanceof Array && data.length) {
      for (var j = 0; j < ids.length; j++) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].id == ids[j]) {
            data.splice(i, 1);
          } else {
            if (data[i].children instanceof Array && data[i].children.length) {
              loop1(data[i].children);
            }
          }
        }
      }
    }
  };
  return loop1(datalist);
};

//递归处理数据
const loopChildren = (datalist: dataSourceType[] = [], checked: Boolean): any => { // 父级选中，子级全选
  // 递归遍历处理数据
  if (!checked) return
  const record: (string | number)[] = [];
  const loop1 = function (data: dataSourceType[]) {
    if (data instanceof Array && data.length) {
      data.map((d) => {
        record.push(d.id);
        if (d.children instanceof Array && d.children.length) {
          loop1(d.children);
        }
      });
    }
  };
  loop1(datalist);
  return [...new Set(record)];
};
const emits = defineEmits(["handleOk", "handleCancle"]);

const buttonMessage = async () => {
  console.log(checkedKeys.value, ' checkedKeys.value')
  let params = {
    targetChannelId: props.modelId,
    sourceChannelIdList: checkedKeys.value,
  };
  await request
    .fetchChannelMerge(params)
    .then((res: detailDataItemType) => {
      if (res.code == "00000 00000") {
        message.success(res.message);

        // emits("handleOk");
        fetchChannelChannelTree();
        emits("handleCancle");
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
  // emits("handleCancle", e);
};
const handleCancle = (e: MouseEvent) => {
  emits("handleCancle", e);
};
const disabledParent = (data: dataSourceType[]) => {
  let id = route.query.channelId;
  let path: any = ''
  if (typeof route.query.parentPath == 'string') {
    path = route.query.parentPath.substring(1, route.query.parentPath.length - 1);
    path = path.split('_')
  }
  path.push(id);
  console.log(path, 'path');
  const loop = function (data: dataSourceType[]) {
    if (data instanceof Array && data.length) {
      return data.map((d: dataSourceType) => {
        d.disabled = path.includes(d.id + '');
        if (path.includes(d.id + '')) {
          console.log(d.id, 'd.id')
          if (d.children instanceof Array && d.children.length) {
            d.children = loop(d.children);
          }
        }
        return d
      })
    }
  };
  loop(data);
}
//onmounted
onMounted(async () => {
  fetchChannelChannelTree();
});
</script>

<style lang="scss" scoped>
.title-box {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: start;
  padding-bottom: 20px;

  .tips {
    width: 370px;
  }

  .right {
    margin-left: 32px;
  }
}

.trasfer-fl {
  display: flex;
  justify-content: space-between;

  .trasfer-center {
    width: 370px;
    padding: 16px 16px 32px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    border-radius: 2px;

  }

  .trasfer-l {}

  .trasfer-r {
    display: block;
  }

  //   align-items: center;
}
</style>
